import { app, BrowserWindow, ipcMain,dialog,Menu,nativeTheme,Notification } from 'electron'
import path from 'path'
import fs from 'fs'
import { fileURLToPath } from 'url'
import RendererManager  from './ipcManager/rendererManager.js'
import UdpService from './services/udp.js'
import ftpService from './services/ftp.js'
import localFilesService from './services/localFiles.js'
try {import('electron-reloader').then(module => {module.default(module, {});});} catch {}
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const udpService = UdpService.getInstance()
let mainWindow = null
function setMenu(){
  const menu = Menu.buildFromTemplate([
    {
      label: "关于",
      submenu: [
        {
          label: '关于',
          click: () => {
            dialog.showMessageBox(mainWindow, {
              title: '关于',
              message: `${app.name} v${app.getVersion()}`,
              buttons: ['确定']
            })
          }
        },
        { type: 'separator' },
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Command+Q' : 'Alt+F4',
          click: () => {
            BrowserWindow.getAllWindows().forEach(window => window.destroy());
            process.exit(0);
          }
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { label: '撤销', role: 'undo' },
        { label: '重做', role: 'redo' },
        { type: 'separator' },
        { label: '剪切', role: 'cut' },
        { label: '复制', role: 'copy' },
        { label: '粘贴', role: 'paste' },
        { label: '删除', role: 'delete' },
        { label: '全选', role: 'selectAll' }
      ]
    },
    {
      label: '视图',
      submenu: [
        { label: '刷新页面',
          accelerator: 'F5',
          click: () => {
            mainWindow.webContents.send('reload-page')
          }
         },
        { type: 'separator' },
        { label: '开发者工具', role: 'toggleDevTools' },
        { type: 'separator' },
        { label: '重置缩放', role: 'resetZoom' },
        { label: '放大', role: 'zoomIn' },
        { label: '缩小', role: 'zoomOut' },
        { type: 'separator' },
        { label: '全屏', role: 'togglefullscreen' }
      ]
    },
    {
      label: '主题',
      submenu: [
        { label: '切换主题', click: () => {
          if(nativeTheme.shouldUseDarkColors){
            nativeTheme.themeSource = 'light'
          }else{
            nativeTheme.themeSource = 'dark'
          }
          mainWindow.webContents.send('dark-mode:change',nativeTheme.shouldUseDarkColors)
         } },
        { label: '系统主题', click: () => {
          nativeTheme.themeSource = 'system'
          mainWindow.webContents.send('dark-mode:change',nativeTheme.shouldUseDarkColors)
        } },
      ]
    }, 
  ])
  return menu
}
function createWindow () {
   mainWindow = new BrowserWindow({
    width: 1000,
    height: 600,
    show: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.cjs'),
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: false,
    }
  })
  mainWindow.once('ready-to-show', () => {
    mainWindow.maximize(); // 窗口最大化
    mainWindow.show(); // 显示窗口
  });
 Menu.setApplicationMenu(setMenu())
 nativeTheme.themeSource = 'dark'
  mainWindow.webContents.send('dark-mode:change',nativeTheme.shouldUseDarkColors)
  mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          "default-src * 'unsafe-inline' 'unsafe-eval'; " +
          "connect-src * ws: wss:; " +
          "img-src * data:; " +
          "script-src * 'unsafe-inline' 'unsafe-eval';"
        ]
      }
    })
  })
  mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    console.error('页面加载失败:', errorCode, errorDescription)
  })
  mainWindow.webContents.openDevTools()
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:3000').catch(err => {
      console.error('开发环境加载失败:', err)
    })  
    mainWindow.webContents.on('did-finish-load', () => {
      mainWindow.webContents.send('dev-reload');
    });
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html')).catch(err => {
      console.error('生产环境加载失败:', err)
    })
  }
  mainWindow.webContents.on('before-input-event', (event, input) => {
    if (input.key === 'F11') {
      mainWindow.setFullScreen(!mainWindow.isFullScreen());
    }
  });
}
function messageTips(message,type){
  mainWindow.webContents.send('message-from-main',{
    status: type,
    message: message
  });
}
ipcMain.handle('get-app-version', () => {
  return app.getVersion()
})
ipcMain.handle('open-file', (event, filePath) => {
  const content = fs.readFileSync(filePath, 'utf8')
  return content
})
ipcMain.handle('dialog:openFile', async () => {
  const {canceled,filePaths} =await dialog.showOpenDialog({
  })
  if(!canceled){
    return filePaths[0]
  }
  return null
})
ipcMain.handle('dark-mode:toggle',()=>{
  if(nativeTheme.shouldUseDarkColors){
    nativeTheme.themeSource = 'light'
  }else{
    nativeTheme.themeSource = 'dark'
  }
  return nativeTheme.shouldUseDarkColors
})
ipcMain.handle('dark-mode:system', () => {
  nativeTheme.themeSource = 'system'
})
ipcMain.on('ondragstart', (event, fileName) => {
  const iconName = path.join(process.cwd(), 'ai.png')
  const filePath = path.join(process.cwd(), fileName)
  event.sender.startDrag({
    file:filePath,
    icon: iconName
  })
})
ipcMain.on('message-to-main', async (event, message) => {
   const {data,commands} = message
  try {
    switch(commands){
      case 'JRLC.UDP.CONNECT':
      await RendererManager.connectUdpServer(message)
      break;
      case 'JRLC.UDP.INPUT':
      await RendererManager.sendInputMessage(message.message)
      break;
      case 'JRLC.FTP.CONNECT':
      await ftpService.connect(data)
      break;
      case 'JRLC.FTP.LIST':
      await ftpService.list(data)
      break;
      case 'JRLC.FTP.CDUP':
      await ftpService.cdup(data)
      break;
      case 'JRLC.FTP.REMOVE':
      await ftpService.remove(data)
      break;
      case 'JRLC.FTP.CLOSE':
      await ftpService.close(data)
      break;
      case 'JRLC.FTP.DOWNLOAD':
      await ftpService.download(data)
      break;
      case 'JRLC.FTP.UPLOAD':
      await ftpService.upload(data)
      break;
      case 'JRLC.LOCAL.DRIVES':
      await localFilesService.getDrives()
      break
      case 'JRLC.LOCAL.PARENT_DIRECTORY':
      await localFilesService.getParentDirectory(data)
      break
      case 'JRLC.LOCAL.LIST':
      await localFilesService.getFileList(data)
      break
    } 
    messageTips('消息已收到','success')
  } catch (error) {
    console.log(error,"error"); 
    messageTips(error,'error')
  }
})
udpService.on('udp-message', (data) => {
  if (mainWindow && !mainWindow.isDestroyed()) {
    mainWindow.webContents.send('udp-message', data)
  }
})
ftpService.on('connected', (data) => {
  console.log('连接成功',111111111);
  mainWindow.webContents.send('message-from-main',{
      cmd:'JRLC.FTP.CONNECT',
      data:data
  });
})
ftpService.on('list-success', (data) => {
  console.log('获取列表成功',data);
  mainWindow.webContents.send('message-from-main',{
      cmd:'JRLC.FTP.LIST',
      data:data
    })
})
ftpService.on('cdup-success', async (data) => {
  console.log('返回上级目录成功',data);
   await ftpService.list(data)
})
ftpService.on('remove-success', async (data) => {
  console.log('删除成功',data);
  await ftpService.list(data)
})
ftpService.on('error', (data) => {
    mainWindow.webContents.send('message-from-main',{
      cmd:'JRLC.FTP.ERROR',
      data:data
    });
})
ftpService.on('download-progress', (data) => {
  console.log('下载进度',data);
  mainWindow.webContents.send('message-from-main', {
    cmd: 'JRLC.FTP.DOWNLOAD_PROGRESS',
    data: data
  })
})
ftpService.on('download-success', (data) => {
  console.log('下载成功',data);
  mainWindow.webContents.send('message-from-main', {
    cmd: 'JRLC.FTP.DOWNLOAD_SUCCESS',
    data: data
  })
})
ftpService.on('upload-progress', (data) => {
  console.log('上传进度',data);
  mainWindow.webContents.send('message-from-main', {
    cmd: 'JRLC.FTP.UPLOAD_PROGRESS',
    data: data
  })
})
ftpService.on('upload-success', (data) => {
  console.log('上传成功',data);
  mainWindow.webContents.send('message-from-main', {
    cmd: 'JRLC.FTP.UPLOAD_SUCCESS',
    data: data
  })
})
localFilesService.on('drives-list', (data) => {
  console.log('获取驱动器成功',data);
  mainWindow.webContents.send('message-from-main',{
    cmd:'JRLC.LOCAL.DRIVES',
    data:data
  });
})
localFilesService.on('list-success', (data) => {
  console.log('获取列表成功',data);
  mainWindow.webContents.send('message-from-main',{
    cmd:'JRLC.LOCAL.LIST',
    data:data
  });
})
localFilesService.on('parent-directory', (data) => {
  console.log('获取上级目录成功',data);
  mainWindow.webContents.send('message-from-main',{
    cmd:'JRLC.LOCAL.PARENT_DIRECTORY',
    data:data
  });
})
const NOTIFICATION_TITLE = 'Basic Notification'
const NOTIFICATION_BODY = 'Notification from the Main process'
function showNotification () {
  new Notification({ title: NOTIFICATION_TITLE, body: NOTIFICATION_BODY }).show()
}
app.whenReady().then(() => {
  createWindow()
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
}).then(showNotification)
app.on('window-all-closed', () => {
  udpService.close()
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

